from flask import Blueprint, request, jsonify, session

from models.Application import Application
from models.Job import Job
from models.Company import Company
from models import db
from datetime import datetime

from models.Resume import Resume

job_bp = Blueprint('job', __name__)

@job_bp.route('/upload_job', methods=['POST'])
def upload_job():
    data = request.get_json()
    user_id = session.get('user_id')
    company = Company.query.filter_by(user_id=user_id).first()
    if not company:
        return jsonify({'message': '公司信息未找到'}), 404

    new_job = Job(
        company_id=company.company_id,
        title=data['title'],
        job_type=data['job_type'],
        description=data['description'],
        requirements=data['requirements'],
        min_salary=data['min_salary'],
        max_salary=data['max_salary'],
        location=data['location'],
        post_date=datetime.strptime(data['post_date'], '%Y-%m-%d').date(),
        expiration_date=datetime.strptime(data['expiration_date'], '%Y-%m-%d').date() if data['expiration_date'] else None
    )
    db.session.add(new_job)
    db.session.commit()
    return jsonify({'message': '职位发布成功', 'job_id': new_job.job_id}), 201

@job_bp.route('/get_jobs', methods=['GET'])
def get_jobs():
    user_id = session.get('user_id')
    company = Company.query.filter_by(user_id=user_id).first()
    if not company:
        return jsonify({'message': '公司信息未找到'}), 404

    jobs = Job.query.filter_by(company_id=company.company_id).all()
    job_list = [{
        'job_id': job.job_id,
        'title': job.title,
        'job_type': job.job_type,
        'min_salary': job.min_salary,
        'max_salary': job.max_salary,
        'location': job.location,
        'status': 'active' if job.expiration_date is None or job.expiration_date > datetime.now().date() else 'completed'
    } for job in jobs]
    return jsonify({'jobs': job_list}), 200

@job_bp.route('/get_all_jobs', methods=['GET'])
def get_all_jobs():
    try:
        user_id = session.get('user_id')
        if not user_id:
            return jsonify({'success': False, 'message': '未登录'}), 401

        # 获取用户的所有简历
        resumes = Resume.query.filter_by(user_id=user_id).all()
        resume_ids = [resume.resume_id for resume in resumes]

        # 获取用户的申请记录
        applications = Application.query.filter(Application.resume_id.in_(resume_ids)).all()
        applied_job_ids = {application.job_id for application in applications}

        jobs = Job.query.all()
        job_list = [{
            'id': job.job_id,
            'title': job.title,
            'job_type': job.job_type,
            'min_salary': job.min_salary,
            'max_salary': job.max_salary,
            'location': job.location,
            'status': 'active' if job.expiration_date is None or job.expiration_date > datetime.now().date() else 'completed',
            'company_name': job.company.company_name,
            'post_date': job.post_date.isoformat(),
            'expiration_date': job.expiration_date.isoformat() if job.expiration_date else None,
            'applied': job.job_id in applied_job_ids  # 是否投递
        } for job in jobs]

        # 打印第一个job的type，用于调试
        if job_list:
            print(job_list[0]['job_type'])

        return jsonify({'jobs': job_list}), 200
    except Exception as e:
        print(f"Error retrieving jobs: {e}")  # 调试信息
        return jsonify({'success': False, 'message': f'获取岗位失败: {str(e)}'}), 500


@job_bp.route('/get_job_details', methods=['GET'])
def get_job_details():
    try:
        job_id = request.args.get('job_id')
        if not job_id:
            return jsonify({'success': False, 'message': '缺少 job_id 参数'}), 400

        job = Job.query.get(job_id)
        if not job:
            return jsonify({'success': False, 'message': '岗位未找到'}), 404

        job_details = {
            'job_id': job.job_id,
            'title': job.title,
            'job_type': job.job_type,
            'description': job.description,
            'requirements': job.requirements,
            'min_salary': job.min_salary,
            'max_salary': job.max_salary,
            'location': job.location,
            'status': 'active' if job.expiration_date is None or job.expiration_date > datetime.now().date() else 'completed',
            'company_name': job.company.company_name,
            'post_date': job.post_date.isoformat(),
            'expiration_date': job.expiration_date.isoformat() if job.expiration_date else None
        }

        return jsonify({'success': True, 'job': job_details}), 200
    except Exception as e:
        print(f"Error retrieving job details: {e}")
        return jsonify({'success': False, 'message': f'获取岗位详情失败: {str(e)}'}), 500
